package com.corn.juc.pool;

import java.util.concurrent.*;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/1/5 11:19
 */

public class ExecutorRejectPolicyDemo {

    public static void main(String[] args) {
        /**
         * 直接丢弃 异常RejectedExecutionException
         */
        testPolicy(new ThreadPoolExecutor.AbortPolicy());
        /**
         * 直接丢入
         * 案例中 coreSize=1 maxCoreSize=1 blockQueue=1
         * 0任务进入调度 1任务进入任务队列 2任务直接丢弃
         */
//        testPolicy(new ThreadPoolExecutor.DiscardPolicy());
        /**
         * 跟Discard策略相反
         * 将workQueue中最早进入队列的丢弃
         */
//        testPolicy(new ThreadPoolExecutor.DiscardOldestPolicy());
        /**
         * 直接抛给调用者执行
         * pool-1-thread-1	task 0 线程池执行
         * main	2 超过线程最大容量
         * pool-1-thread-1	task 1 任务队列拿出来执行
         */
//        testPolicy(new ThreadPoolExecutor.CallerRunsPolicy());
    }


    private static void testPolicy(RejectedExecutionHandler handler) {
        ExecutorService executor = new ThreadPoolExecutor(1, 1,
                1, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1),
                Executors.defaultThreadFactory(),
                handler);

        for (int i = 0; i < 3; i++) {
            int finalI = i;
            executor.submit(() -> {
                System.out.println(Thread.currentThread().getName() + "\t task" + finalI);
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }

}
